<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>数据管理系统</title>
  <link rel="stylesheet" href="css/user.css">
  <script src="js/jquery.min.js" ></script>
</head>
<body>
<div class="container">
  <h1>数据管理系统</h1>

  <!-- 搜索功能 -->
  <div class="search-box">
    <input type="text" id="searchInput" placeholder="输入关键字搜索..." style="width: 300px; padding: 10px;">
    <button onclick="searchData()">搜索</button>
    <button onclick="openAddModel()">添加</button>

  </div>



  <!-- 数据列表 -->
  <h2>数据列表</h2>
  <table id="dataTable">
    <thead>
    <tr>
      <th>ID</th>
      <th>姓名</th>
      <th>邮箱</th>
      <th>年龄</th>
      <th>性别</th>
      <th>操作</th>
    </tr>
    </thead>
    <tbody id="tableBody">
    <!-- 数据将通过JavaScript动态加载 -->
    </tbody>
  </table>
</div>
<!-- 添加数据表单 -->
<div class="form-container">

</div>
<!-- 编辑模态框 -->
<div id="editModal" class="modal">
  <div class="modal-content">
    <span class="close" onclick="closeModal()">&times;</span>
    <h2>编辑数据</h2>
    <input type="hidden" id="editId">
    <div class="form-group">
      <label for="editName">姓名:</label>
      <input type="text" id="editName" required>
    </div>
    <div class="form-group">
      <label for="editEmail">邮箱:</label>
      <input type="email" id="editEmail" required>
    </div>
    <div class="form-group">
      <label for="editAge">年龄:</label>
      <input type="number" id="editAge" min="0" required>
    </div>
    <div class="form-group">
      <label for="editGender">性别:</label>
      <select id="editGender">
        <option value="男">男</option>
        <option value="女">女</option>
        <option value="其他">其他</option>
      </select>
    </div>
    <button onclick="updateData()">更新</button>
    <button onclick="closeModal()">取消</button>
  </div>
</div>
<!--添加模态框-->
<div id="addModal" class="modal">
  <div class="modal-content">
    <span class="close" onclick="closeModal()">&times;</span>
    <h2>添加新数据</h2>
    <div class="form-group">
      <label for="name">姓名:</label>
      <input type="text" id="name" required>
    </div>
    <div class="form-group">
      <label for="email">邮箱:</label>
      <input type="email" id="email" required>
    </div>
    <div class="form-group">
      <label for="provinceId">省份id:</label>
      <input type="number" id="provinceId" min="0" required>
    </div>
    <div class="form-group">
      <label for="sex">性别:</label>
      <select id="sex">
        <option value="男">男</option>
        <option value="女">女</option>
        <option value="其他">其他</option>
      </select>
    </div>
    <button onclick="addData()">添加</button>
    <button onclick="clearForm()">清空</button>




  </div>
</div>

<script>
  let userData =[];
  function loadUserData(username){
    alert(username);
    $.ajax({
      type: "get",
      url: "/user/getUserList", // 你的请求链接,servlet 路径
      dataType:"json",
      data:{
        username:username
      },
      success:function (data) {
        userData =data;
        let userListHtml='';
        $.each(data,function (index,item){

          userListHtml +=`<tr>

                    <td>${item.id}</td>
                    <td>${item.username}</td>
                    <td>${item.email}</td>
                    <td>${item.provinceId}</td>
                    <td>${item.sex}</td>
                    <td class="action-buttons">
                        <button class="edit" onclick="openEditModal(${item.id})">编辑</button>
                        <button class="delete" onclick="deleteData(${item.id})">删除</button>

                    </td>
                    </tr>
                `
        })

        $('#tableBody').html(userListHtml);


      },error:function (err){
        // alert("1111");
        console.log(err);

      }
    })
  }
  $(document).ready(function () {
      //加载用户列表数据
      loadUserData();
  })



  // 添加数据
  function addData() {
    let name = $("#name").val();
    let email = $("#email").val();
    let provinceId = $("#provinceId").val();
    let sex = $("#sex").val();

    if (!name || !email || !provinceId) {
      alert('请填写所有必填字段');
      return;
    }

    //添加数据到数据库
    const userData = {
      username: name,
      email: email,
      provinceId:provinceId,
      sex:sex
    };

    $.ajax({
        url: '/user/addUser', // 替换为你的后端接口地址
        type: 'put', // 请求类型
        contentType: 'application/json', // 指定请求体格式为 JSON
        data: JSON.stringify(
               userData
        ), // 将 JavaScript 对象转换为 JSON 字符串
        success: function(response) {
          alert("添加成功！");
          document.getElementById('addModal').style.display = 'none';
          console.log('用户数据成功发送:', response);
          // 处理成功情况
        },
        error: function(xhr, status, error) {
          console.error('发送用户数据失败:', status, error);
          // 处理错误情况
        }
      });

     //刷新列表数据
    loadUserData();
  }

  // 清空表单
  function clearForm() {
    document.getElementById('name').value = '';
    document.getElementById('email').value = '';
    document.getElementById('age').value = '';
    document.getElementById('gender').value = '男';
  }

  // 删除数据
  function deleteData(id) {
    if (confirm('确定要删除这条数据吗？')) {
      //userData = userData.filter(item => item.id !== id);
      //删除数据库的列数据

      $.ajax({
        url: '/user/deleteUser/'+id, // Keep the URL
        type: 'DELETE', // Request type
        //data: { id: id }, // Send id as query parameter
        success: function(response) {
          alert("删除成功！");
          loadUserData(); // Refresh the list
        },
        error: function(xhr, status, error) {
          console.error('发送用户数据失败:', status, error);
          // Handle errors
        }
      });
    }
  }

  // 打开编辑模态框
  function openEditModal(id) {
    console.log(userData);
    const item = userData.find(item => item.id === id);
    if (!item) return;

    document.getElementById('editId').value = item.id;
    document.getElementById('editName').value = item.name;
    document.getElementById('editEmail').value = item.email;
    document.getElementById('editAge').value = item.provinceId;
    document.getElementById('editGender').value = item.sex;

    document.getElementById('editModal').style.display = 'block';
  }

  function openAddModel(){
    document.getElementById('addModal').style.display = 'block';

  }

  // 关闭模态框
  function closeModal() {
    document.getElementById('editModal').style.display = 'none';
    document.getElementById('addModal').style.display = 'none';

  }

  // 更新数据
  function updateData() {
    const id = parseInt(document.getElementById('editId').value);
    const name = document.getElementById('editName').value;
    const email = document.getElementById('editEmail').value;
    const provinceId = document.getElementById('editAge').value;
    const sex = document.getElementById('editGender').value;

    if (!name || !email || !provinceId) {
      alert('请填写所有必填字段');
      return;
    }
    //更新数据
    const  userData={
      id:id,
      username: name,
      email: email,
      provinceId:provinceId,
      sex:sex
    }
    $.ajax({
      url: '/user/updateUser', // 替换为你的后端接口地址
      type: 'post', // 请求类型
      contentType: 'application/json', // 指定请求体格式为 JSON
      data: JSON.stringify(
              userData
      ), // 将 JavaScript 对象转换为 JSON 字符串
      success: function(response) {
        alert("修改成功！");
        closeModal();
        // 处理成功情况
      },
      error: function(xhr, status, error) {
        console.error('发送用户数据失败:', status, error);
        // 处理错误情况
      }
    });

    //刷新列表数据
    loadUserData();

    closeModal();

    }



  // 搜索数据
  function searchData() {
    debugger;
    const keyword = document.getElementById('searchInput').value;

    loadUserData(keyword);


  }

  // 点击模态框外部关闭模态框
  window.onclick = function(event) {
    const modal = document.getElementById('editModal');
    if (event.target === modal) {
      closeModal();
    }
  }
</script>
</body>
</html>